<?php

use Yaf\Registry;
use models\Business\Tbk\TbkSdk\Tbk;
use models\Business\Oauth;
use Yaf\Session;


class TaobaoController extends ApiBaseController
{
    public function loginAction() {
        // 获取第三方平台的授权登录地址并跳转
        $url = Tbk::taobaoLogin();
        header('location:' . $url);

    }

    public function getUserInfoAction() {
        var_dump(__METHOD__);
        $parameters = Registry::get('parameters');
        $redirect_url = isset($parameters['redirect_url']) && !empty($parameters['redirect_url']) ? $parameters['redirect_url'] : '';

        Session::getInstance()->set('redirect_url', $redirect_url);

        $url = Tbk::taobaoLogin();
        header('location:' . $url);
    }

    public function OauthAction() {
        $parameters = Registry::get('parameters');
        $redirect_url = Session::getInstance()->get('redirect_url');
        if (empty($parameters['code']) || $parameters['state'] != \Yaf\Session::getInstance()->get('YL_TAOBAO_STATE'))
            throw new Exception('授权出错');

        $user_info = Tbk::getUserInfo($parameters['code'],Session::getInstance()->get('YL_TAOBAO_STATE'));

        if (! empty($redirect_url)) {
            $param = [
                'open_id' => $user_info['open_id'],
                'union_id' => $user_info['union_id'],
                'access_token' => $user_info['access_token'],
                'expired_at' => $user_info['expired_at'],
                'type' => $user_info['type'],
            ];
            header('location: ' . $redirect_url . '&' . http_build_query($param));
        } else {
            // 注册
            $member_info = Oauth::login($user_info);
            $member_info['type'] = 4;

            header("Location: " . Registry::get('config')['application']['member']['host'] . '?jwt=' . $member_info['jwt'] . '&login_type=' . $member_info['type']);
        }
//        echo json_encode($member_info);

        /*try {
            $client = new WsClient('127.0.0.1', 19992, '/');
            if($client->connect())
                $client->sendJson(['action' => 'speakTo', 'state' => $state, 'msg' => 'login successfully',
                    'user_info' => $member_info]);
            else
                Registry::get('user_log')->err(__METHOD__ . " - websocket链接失败");
        } catch (Exception $e) {
            Registry::get('user_log')->err(__METHOD__ . " - 链接失败: " . $e->getMessage());
        } finally {
            return $this->_responseJson($member_info);
        }*/

    }
}
